package com.example.rocketmq;

import code.example.tool.LogFactory;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import sun.rmi.log.ReliableLog;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MyProducer {

    private String topic ="MqTopic";
    private String tag = "mqTag";
    private String group = "Test";
    DefaultMQProducer  mqProducer = null;
    public MQProducer getMQProducer() {

        if(this.mqProducer == null){
            try {
                DefaultMQProducer mqProducer = new DefaultMQProducer(group);
                mqProducer.setNamesrvAddr("localhost:9876");
                mqProducer.start();
                this.mqProducer = mqProducer;
                LogFactory.getLog().info("start producer success");
            }catch (Exception e){
                LogFactory.getLog().error("start producer fail:",e);
            }
        }

        return this.mqProducer;
    }
    public void send(String message) throws Exception {
        MQProducer mqProducer  = this.getMQProducer();
        Message msg = new Message(topic /* Topic */,
                tag /* Tag */,
                message.getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
        );
        SendResult sendResult =  mqProducer.send(msg);
        LogFactory.getLog().info("sendResult:"+sendResult);
    }
    public void start(){
        ScheduledExecutorService scheduledExecutorService =  Executors.newScheduledThreadPool(1);
        scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
            int count = 0;
            @Override
            public void run() {
                try{
                    this.count ++;
                    send("mq messsage"+this.count);
                }catch (Exception e){
                    LogFactory.getLog().error(e);
                }
            }
        },5,1, TimeUnit.SECONDS);
    }
    public static void main(String args [] ){

    }
}
